package net.maku.module.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import net.maku.module.dao.AgVisitorVolumeMapper;
import net.maku.module.entity.AgVisitorVolume;
import net.maku.module.query.AgVisitorVolumeQuery;
import net.maku.module.service.AgVisitorVolumeService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import static net.maku.module.util.DateUtils.getEndDateWithLastDay;

@Service
@AllArgsConstructor
public class AgVisitorVolumeServiceImpl extends ServiceImpl<AgVisitorVolumeMapper, AgVisitorVolume> implements AgVisitorVolumeService {

    private final AgVisitorVolumeMapper agVisitorVolumeMapper;

    @Override

    public List<Map<String, Object>> getVisitorVolumeByParam(AgVisitorVolumeQuery agVisitorVolumeQuery) {
        // 构建查询条件
        QueryWrapper<AgVisitorVolume> queryWrapper = buildQueryWrapper(agVisitorVolumeQuery);

        // 执行查询
        return agVisitorVolumeMapper.selectMaps(queryWrapper);
    }

    @Override
    public List<Map<String, Object>> queryByParam(AgVisitorVolumeQuery agVisitorVolumeQuery) {
        return agVisitorVolumeMapper.queryByParam(agVisitorVolumeQuery);
    }

    /**
     * 构建查询条件
     * @param query 查询参数
     * @return 查询条件
     */
    private QueryWrapper<AgVisitorVolume> buildQueryWrapper(AgVisitorVolumeQuery query) {
        QueryWrapper<AgVisitorVolume> queryWrapper = new QueryWrapper<>();

        String dateFormat = "%Y";
        String startDate;
        String endDate;

        if ("month".equals(query.getType())) {
            dateFormat = "%Y-%m";
            startDate = query.getStartDate() + "-01";
            endDate = getEndDateWithLastDay(query.getEndDate());
        }else {
            startDate = query.getStartDate() + "-01-01";
            endDate = query.getEndDate() + "-12-31";
        }

        queryWrapper.select(String.format("DATE_FORMAT(create_time, '%s') as createTime", dateFormat), "count(*) as \"number\"")
                .eq(ObjectUtil.isNotNull(query.getWebsiteId()),"website_id", query.getWebsiteId())
                .eq(ObjectUtil.isNotNull(query.getTenantId()),"tenant_id", query.getTenantId())
                .isNotNull(query.getName())
                .groupBy(String.format("DATE_FORMAT(create_time, '%s')", dateFormat))
                .between("create_time", startDate, endDate)
                .orderByDesc(String.format("DATE_FORMAT(create_time, '%s')", dateFormat));

        return queryWrapper;
    }
}
